import axios, { AxiosInstance, AxiosResponse, AxiosError } from 'axios';
import { showDialog } from 'vant';
import router from "../router";

// 响应数据接口
interface ApiResponse<T = any> {
    code: number
    message: string
    data?: T
}

// 用户信息接口
interface UserInfo {
    token: string
    [key: string]: any
}

// 声明全局APP_CONFIG类型
declare global {
    interface Window {
        APP_CONFIG: {
            apiBaseUrl: string;
            [key: string]: any;
        }
    }
}

// API基础URL
const backendAPI = { 
    baseUrl: window.APP_CONFIG?.apiBaseUrl || 'http://localhost:8081' 
};

// 创建不同的axios实例
let instance: AxiosInstance = axios.create({ baseURL: backendAPI.baseUrl });
let withToken: AxiosInstance = axios.create({ baseURL: backendAPI.baseUrl });
let withTokenNoIntercept: AxiosInstance = axios.create({ baseURL: backendAPI.baseUrl });

// 通用响应处理
let commonResponse = function (res: AxiosResponse<ApiResponse>): Promise<AxiosResponse<ApiResponse>> {
    if (res.data.code === 100) {
        return Promise.resolve(res);
    } else {
        showDialog({ message: "请求错误，服务器返回错误信息：" + res.data.message });
        return Promise.reject(res.data.message);
    }
}

// 通用错误处理
let commonErr = function (err: AxiosError): Promise<never> {
    console.log(err);
    showDialog({ message: "请求发生错误：" + err });
    return Promise.reject(err);
}

// 无token实例拦截器
instance.interceptors.response.use(commonResponse, commonErr);

// 带token实例请求拦截器
withToken.interceptors.request.use(
    (config: any) => {
        if (localStorage.user_info) {
            try {
                const userInfo: UserInfo = JSON.parse(localStorage.user_info);
                if (userInfo.data.passwordHash && typeof userInfo.data.passwordHash === 'string') {
                    config.headers["Authorization"] = userInfo.data.passwordHash;
                }
            } catch (error) {
                console.error('解析用户信息失败:', error);
                localStorage.removeItem('user_info');
            }
        }
        return config;
    },
    (err: any) => {
        showDialog({ message: '请求超时' });
        return Promise.reject(err);
    }
);

// 带token实例响应拦截器
withToken.interceptors.response.use(
    (res: any) => {
        if (res.data.code === 100) {
            return res.data;
        } else if (res.data.code === 102) {
            showDialog({
                message: "登录已过期，请重新登录",
                confirmButtonText: "前往登录",
            }).then(() => {
                localStorage.removeItem('user_info');
                router.push("/login");
            }).catch(() => {
                // 留在当前页
            });
            return Promise.reject(res.data.message);
        } else if (res.data.code === 103) {
            showDialog({
                message: "密码错误，请重新输入",
                confirmButtonText: "确认",
            });
            return Promise.reject(res.data.message);
        } else {
            showDialog({ message: "请求错误，服务器返回：" + res.data.message });
            return Promise.reject(res.data.message);
        }
    }, 
    (err: any) => {
        console.log(err);
        showDialog({ message: "发生错误！" + err });
        return Promise.reject(err);
    }
);

// 带token但无拦截器实例请求拦截器
withTokenNoIntercept.interceptors.request.use(
    (config: any) => {
        if (localStorage.user_info) {
            const userInfo: UserInfo = JSON.parse(localStorage.user_info);
            if (userInfo.data.passwordHash) {
                config.headers["Authorization"] = userInfo.data.passwordHash;
            }
        }
        return config;
    },
    (err: any) => {
        showDialog({ message: '请求超时' });
        return Promise.reject(err);
    }
);

// 带token但无拦截器实例响应拦截器
withTokenNoIntercept.interceptors.response.use(
    (res: any) => {
        if (res.data.code === 100) {
            return res.data;
        } else if (res.data.code === 102) {
            return Promise.reject("权限不足或登录已过期");
        } else {
            showDialog({ message: "请求错误，服务器返回：" + res.data.message });
            return Promise.reject(res.data.message);
        }
    }, 
    (err: any) => {
        showDialog({ message: "发生错误！" + err });
        return Promise.reject(err);
    }
);

// API实例
const api = {
    // =============== 用户认证模块 ===============
    login(user: any) {
        return instance.post("/users/login", user);
    },
    
    register(user: any) {
        return instance.post("/users/register", user);
    },
    
    forgotPassword(user: any) {
        return instance.post("/users/forgotPassword", user);
    },
    
    checkLogin() {
        return withToken.get("/users/checkLogin");
    },

    logout() {
        return withToken.post("/users/logout");
    },
    
    // =============== 用户信息模块 ===============
    getUserProfile() {
        return withToken.get("/users/profile");
    },
    
    updateUserProfile(userData: any) {
        return withToken.post("/users/updateprofile", userData);
    },
    
    uploadAvatar(formData: any) {
        return withToken.post("/users/avatar", formData);
    },
    
    getAvatarById(userId: any) {
        return instance.get(`/users/avatar/${userId}`);
    },
    
    updatePassword(passwordData: any) {
        return withToken.post("/users/password", passwordData);
    },
    
    updateUserSettings(settingsData: any) {
        return withToken.post("/users/settings", settingsData);
    },
    
    clearUserCache() {
        return withToken.post("/users/clear-cache");
    },
    
    // =============== 地址管理模块 ===============
    getUserAddresses() {
        return withToken.get("/users/addresses");
    },
    
    addAddress(addressData: any) {
        return withToken.post("/users/addresses", addressData);
    },
    
    updateAddress(addressId: number, addressData: any) {
        return withToken.put(`/users/addresses/${addressId}`, addressData);
    },
    
    deleteAddress(addressId: number) {
        return withToken.delete(`/users/addresses/${addressId}`);
    },
    
    setDefaultAddress(addressId: number) {
        return withToken.put(`/users/addresses/${addressId}/default`);
    },
    
    // =============== 商店模块 ===============
    getStoreList(params: any = {}) {
        const query = new URLSearchParams(params).toString();
        return instance.get(`/stores?${query}`);
    },
    
    getStoreDetail(storeId: number) {
        return instance.get(`/stores/${storeId}`);
    },
    
    getNearbyStores(latitude: number, longitude: number, radius: number = 5) {
        return instance.get(`/stores/nearby?latitude=${latitude}&longitude=${longitude}&radius=${radius}`);
    },
    
    getStoreTags() {
        return instance.get("/stores/tags");
    },
    
    // =============== 商品模块 ===============
    getCategories() {
        return instance.get("/categories");
    },
    
    getProducts(params: any = {}) {
        const query = new URLSearchParams(params).toString();
        return instance.get(`/products?${query}`);
    },
    
    getStoreProducts(storeId: number, params: any = {}) {
        const query = new URLSearchParams(params).toString();
        return instance.get(`/stores/${storeId}/products?${query}`);
    },
    
    getProductDetail(productId: number) {
        return instance.get(`/products/${productId}`);
    },
    
    searchProducts(keyword: string, params: any = {}) {
        const queryParams = { ...params, keyword };
        const query = new URLSearchParams(queryParams).toString();
        return instance.get(`/products/search?${query}`);
    },
    
    // =============== 视频模块 ===============
    getVideos(params: any = {}) {
        return instance.get('/videos/list', { params });
    },
    
    getVideoDetail(videoId: number) {
        return instance.get(`/videos/${videoId}`);
    },
    
    getRecommendedVideos(videoId: number) {
        return instance.get(`/videos/${videoId}/recommended`);
    },
    
    likeVideo(videoId: number) {
        return withToken.post(`/videos/${videoId}/like`);
    },
    getVideoCategories() {
        return instance.get('/videos/categories');
    },
    
    // =============== 购物车模块 ===============
    getCartItems() {
        return withToken.get("/cart");
    },
    
    addToCart(productId: number, quantity: number = 1) {
        return withToken.post("/cart/items", { product_id: productId, quantity });
    },
    
    updateCartItemQuantity(cartItemId: number, quantity: number) {
        return withToken.put(`/cart/items/${cartItemId}`, { quantity });
    },
    
    removeFromCart(cartItemId: number) {
        return withToken.delete(`/cart/items/${cartItemId}`);
    },
    
    updateCartItemSelection(cartItemId: number, selected: boolean) {
        return withToken.put(`/cart/items/${cartItemId}/select`, { selected: selected ? 1 : 0 });
    },
    
    // =============== 订单模块 ===============
    createOrder(orderData: any) {
        return withToken.post("/orders", orderData);
    },
    
    getOrders(status?: string) {
        const query = status ? `?status=${status}` : '';
        return withToken.get(`/orders${query}`);
    },
    
    getOrderDetail(orderId: number) {
        return withToken.get(`/orders/${orderId}`);
    },
    
    cancelOrder(orderId: number) {
        return withToken.put(`/orders/${orderId}/cancel`);
    },
    
    confirmReceipt(orderId: number) {
        return withToken.put(`/orders/${orderId}/confirm`);
    },
    
    // =============== 评论模块 ===============
    getProductReviews(productId: number, params: any = {}) {
        const query = new URLSearchParams(params).toString();
        return instance.get(`/products/${productId}/reviews?${query}`);
    },
    
    addProductReview(productId: number, reviewData: any) {
        return withToken.post(`/products/${productId}/reviews`, reviewData);
    },
    
    // =============== 收藏模块 ===============
    getFavorites(type: string) {
        return withToken.get(`/favorites?type=${type}`);
    },
    
    addFavorite(type: string, id: number) {
        return withToken.post("/favorites", { type, id });
    },
    
    removeFavorite(favoriteId: number) {
        return withToken.delete(`/favorites/${favoriteId}`);
    },
    
    checkFavorite(type: string, id: number) {
        return withTokenNoIntercept.get(`/favorites/check?type=${type}&id=${id}`);
    },
    
    // =============== 支付模块 ===============
    submitPayment(paymentData: any) {
        return withToken.post("/payments", paymentData);
    },
    
    getPaymentMethods() {
        return instance.get("/payments/methods");
    }
}

export default api;